from fastapi import APIRouter, Body
from pydantic import BaseModel
from .config import app, dblock
import datetime as dt
from dataclasses import asdict

router = APIRouter(prefix="/api/elective", tags=["elective"])

@router.get("/list")
def list_elective():
    with dblock() as db:
        db.execute('''
            SELECT e.sn, e.stu_sn, s.stu_name AS stu_name, e.class_sn, c.name AS class_name, e.elective_time
            FROM elective e
            LEFT JOIN student s ON e.stu_sn = s.sn
            LEFT JOIN class c ON e.class_sn = c.sn
            ORDER BY e.sn
        ''')
        data = []
        for row in db:
            d = asdict(row)
            data.append(d)
    return data

class ElectiveBatch(BaseModel):
    class_sn: int
    stu_sn_list: list[int]

@router.post("")
def batch_elective(data: ElectiveBatch):
    now = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with dblock() as db:
        for stu_sn in data.stu_sn_list:
            db.execute(
                """
                INSERT INTO elective (class_sn, stu_sn, elective_time)
                VALUES (%(class_sn)s, %(stu_sn)s, %(elective_time)s)
                ON CONFLICT (class_sn, stu_sn) DO NOTHING
                """,
                {"class_sn": data.class_sn, "stu_sn": stu_sn, "elective_time": now}
            )
    return {"success": True, "count": len(data.stu_sn_list)}

# 其他增删改查API可后续补充 

# 注册路由到app，确保接口可访问
app.include_router(router) 